package ru.cod.rs.objects.gameobjects;

import java.util.ArrayList;
import java.util.List;

import ru.cod.rs.interfaces.Game;
import ru.cod.rs.interfaces.gameInterface.Unit;

public class GameWorld {

	private Game game;

	private List<Unit> units;

	public GameWorld(Game g) {

		game = g;
		units = new ArrayList<Unit>();
		addInitUnits();
	}

	public void update() {

		for (Unit unit : units) {

			testCollision(unit);
			unit.update();
		}
	};

	public void render() {

		for (Unit unit : units) {
			unit.render();
		}
	}

	private void addInitUnits() {

		units.add(new Castle(Side.ALLY, game));
		units.add(new Castle(Side.ENEMY, game));

		units.add(new SimpleUnit(Side.ALLY, game));
		units.add(new SimpleUnit(Side.ENEMY, game));
	}

	public void addSimpleUnit() {
		units.add(new SimpleUnit(Side.ALLY, game));
	}

	private boolean isBumpInto(Unit a, Unit e) {
		int x1 = ((AbstractUnit) a).getX(), w1 = ((AbstractUnit) a).getWidth();
		int x2 = ((AbstractUnit) e).getX();
		if (x2 > x1 && x2 < x1 + w1) {
			return true;
		}
		return false;
	}

	private void testCollision(Unit u) {
		if (!units.isEmpty() && ((AbstractUnit) u).getSide().equals(Side.ALLY)) {
			for (Unit unit : units) {
				if (((AbstractUnit) unit).getSide().equals(Side.ENEMY)) {
					if (isBumpInto(u, unit)) {
						units.add(new SimpleUnit(Side.ENEMY, game));
					}
				}
			}
		}
	}

}
